package com.boot.notes.rocketmq.transactionMsg;

import com.alibaba.fastjson.JSON;
import com.boot.common.constant.rocket.TopicConstant;
import com.boot.common.enums.OrderEnums;
import com.boot.common.utils.R;
import com.boot.modules.admin.service.OrderService;
import com.boot.notes.rocketmq.transactionMsg.entity.Order;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @className: MessageController
 * @auther: mkq
 * @date: 2022/01/22 10:29
 * @desctiption: TODO
 * @version: 1.0
 */
public class MessageController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    /**
     * 步骤一：
     * 描述：发送订单消息
     *
     * @param order
     * @return
     */
    @RequestMapping("/pay")
    public R pay(@RequestBody Order order) {
        String orderRequest = JSON.toJSONString(order);
        Message message = MessageBuilder.withPayload(orderRequest).build();
        try {
            // destination即为主题topic
            TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(
                    TopicConstant.TRANSACTION_TOPIC,
                    MessageBuilder.withPayload(order).build(),
                    orderRequest);
            System.out.println(sendResult);
        } catch ( MessagingException e) {
            e.printStackTrace();
            // 发生异常，状态变更为“已退款”
            orderService.updateOrderState(order.getId(), OrderEnums.REFUND.getCode());
        }
        return R.ok();
    }


}
